<template>
  <view class="p-wrapper" @click="gotoGoods">
    <view class="p-img">
      <image :src="goodsData.cover_url"></image>
    </view>
    <view class="p-info">
      <view class="p-title">{{ goodsData.name }}</view>
      <view class="p-sale">已售{{ goodsData.sell_count }}</view>
    </view>
    <view class="p-price-wrapper">
      <view class="p-price">
        <text class="p-price-smail">￥</text>
        {{ goodsData.price.big }}
        <text class="p-price-smail">.{{ goodsData.price.small }}</text>
      </view>
      <view class="p-postage" v-if="goodsData.logistics_price == null || goodsData.logistics_price == 0">包邮</view>
    </view>
  </view>
</template>

<script>
import { formatPrice } from '../../utils/formatPrice'
export default {
  props: {
    goods: {
      type: Object,
      default: {
        id: '',
        price: 0,
        name: '',
        cover_url: '',
        logistics_price: null,
        selled_count: 0
      }
    }
  },

  components: {},
  data() {
    return {
      goodsData: null
    }
  },
  watch: {
    goods: {
      handler(n, o) {
        this.goodsData = { ...n }

        // 处理价格
        this.goodsData.price = formatPrice(n.price)

        // 截断超过6个字的名称
        this.goodsData.name = this.goodsData.name.length > 6 ? this.goodsData.name.slice(0, 8) : this.goodsData.name
      },
      deep: true,
      immediate: true // 🚀 让 watch 在初始化时也执行一次
    }
  },
  methods: {
    gotoGoods() {
      uni.navigateTo({
        url: '/pages/goods/index?id=' + this.goodsData.id + '&coverUrl=' + this.goodsData.cover_url
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.p-wrapper {
  width: 350upx;
  height: 450upx;
  display: inline-flex;
  margin-left: calc(50upx / 3);
  margin-bottom: calc(50upx / 3);
  background-color: #fff;
  padding: 15upx;
  box-sizing: border-box;

  border-radius: 15upx;
  box-shadow: $def-shadow;
  justify-content: center;
  align-items: flex-start;
  flex-direction: column;

  .p-img {
    background-color: #808080;
    width: 100%;
    height: 300upx;
    image {
      width: 100%;
      height: 100%;
    }
  }

  .p-info,
  .p-price-wrapper {
    width: 100%;
    display: flex;
    justify-content: space-between;
    align-items: center;
    font-size: 30upx;
    margin-top: 10upx;
  }

  .p-sale,
  .p-postage {
    font-size: 25upx;
  }

  .p-postage {
    padding: 5upx 15upx;
    border-radius: 5upx;
    background-color: $uni-color-warning;
    color: #fff;
  }

  .p-sale {
    color: $uni-text-color-grey;
  }

  .p-price {
    color: #f23e37;
    font-size: $def-price;
    .p-price-smail {
      font-size: $def-small-price;
    }
  }
}
</style>
